package com.get.backstage.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.get.backstage.common.result.R;
import com.get.backstage.common.security.JwtTokenProvider;
import com.get.backstage.user.entity.User;
import com.get.backstage.user.service.UserService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录类
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/login")
@Slf4j
public class LoginController {
    @Autowired
    AuthenticationManagerBuilder authenticationManagerBuilder;
    @Autowired
    JwtTokenProvider jwtTokenProvider;
    @Autowired
    UserService userService;

    @PostMapping("/username")
    public R usernameLogin(User user,HttpServletResponse httpServletResponse){
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
        Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String token = jwtTokenProvider.createJwtToken(authentication);
        httpServletResponse.setHeader("Authorization", "Bearer" + " " + token);

         user = userService.getOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        return R.success(user);
    }



















}
